from flask import Flask, jsonify, request
import joblib
from sklearn.preprocessing import StandardScaler
import pandas as pd

app = Flask(__name__)

# 加载模型
model = joblib.load("smote_xgb.pkl")

# API接口
@app.route('/predict', methods=['POST'])
def predict():
    try:
        # 获取POST请求中的数据
        data = request.json
        print(data)

        # 转换为Pandas对象并填充缺失值
        df = pd.DataFrame([data], index=[0])
        df['bmi'] = df['bmi'].fillna(0)

        # 数据标准化
        scaler = StandardScaler()
        scaler.fit(df)
        data_scaled = scaler.transform(df)

        # 预测
        prediction = model.predict(data_scaled)

        # 返回预测结果
        response = {'prediction': int(prediction[0])}
        print(prediction)
        return jsonify(response)
    except Exception as e:
        print(e)
        return {"err":"请按照要求传递参数"}

if __name__ == '__main__':
    app.run()